Печать

QR-Code dieser Seite

Копия статьи "Форматирование столбцов в списках и библиотеках SharePoint". URL: https://docs.microsoft.com/ru-ru/sharepoint/dev/declarative-customization/column-formatting#how-is-column-formatting-different-than-the-field-customizer

!-- -->

Форматирование столбцов позволяет настраивать отображение полей в списках и библиотеках SharePoint.You can use column formatting to customize how fields in SharePoint lists and libraries are displayed. Для этого создается объект JSON, который описывает элементы, отображаемые при включении поля в список, и стили, применяемые к этим элементам.To do this, you construct a JSON object that describes the elements that are displayed when a field is included in a list view, and the styles to be applied to those elements. При форматировании столбцов данные в элементе списка или файле остаются неизменными. Изменяется только их внешний вид.The column formatting does not change the data in the list item or file; it only changes how it’s displayed to users who browse the list. Настраивать поля с помощью форматирования столбцов могут все, кто может создавать списки и управлять ими.Anyone who can create and manage views in a list can use column formatting to configure how view fields are displayed.

Например, список с полями "Заголовок", "Трудозатраты", "Кому назначено" и "Состояние" без настройки может выглядеть так:For example, a list with the fields Title, Effort, Assigned To, and Status with no customizations applied might look like this:

Список SharePoint с четырьмя столбцами без форматирования

Список с полями Трудозатраты, Кому назначено и Состояние, настроенные с помощью функции форматирования столбцов, может выглядеть так:A list with the appearance of the Effort, Assigned To, and Status fields customized via column formatting might look like this:

Список SharePoint с тремя отформатированными столбцами

Совет

Примеры из этой статьи и много других примеров с сайта сообщества доступны в репозитории GitHub, посвященном определениям форматирования столбцов с открытым кодом.Samples demonstrated in this article and numerous other community samples are available from a GitHub repository dedicated for open-sourced column formatting definitions. Вы можете найти эти примеры в репозитории sp-dev-column-formatting организации SharePoint на сайте GitHub.You can find these samples from the sp-dev-column-formatting repository at SharePoint GitHub organization.

Чем форматирование столбцов отличается от настройщика полей?How is column formatting different than the Field Customizer?

Как форматирование столбцов, так и расширения Настройщик полей SharePoint Framework позволяют настраивать поля в списках SharePoint.Both column formatting and SharePoint Framework Field Customizer extensions enable you to customize how fields in SharePoint lists are displayed. Настройщик полей — универсальный инструмент, так как позволяет создавать любой код для управления отображением поля.The Field Customizer is more powerful because you can use it to write any code that you want to control how a field is displayed.

Форматирование столбцов проще и доступнее,Column formatting is more easily and broadly applied. но не так универсально, так как не позволяет создавать пользовательский код и поддерживает только предопределенные элементы и атрибуты.However, it is less flexible, because it does not allow for custom code; it only allows for certain predefined elements and attributes.

В таблице ниже сравниваются форматирование столбцов и настройщик полей.The following table compares column formatting and the Field Customizer.

Тип поляField type Форматирование столбцовColumn formatting Настройщик полейField Customizer
Условное форматирование на основе значений элементов и диапазонов значенийConditional formatting based on item values and value ranges ПоддерживаетсяSupported ПоддерживаетсяSupported
Ссылки на действияAction links Поддержка статических гиперссылок, которые не запускают сценарииSupport for static hyperlinks that do not launch script Поддержка всех гиперссылок, в том числе запускающих пользовательские сценарииSupport for any hyperlink, including those that invoke custom script
Визуализация данныхData visualizations Поддержка простой визуализации, которую можно выразить с помощью HTML и CSSSupport for simple visualizations that can be expressed using HTML and CSS Поддержка произвольной визуализации данныхSupport for arbitrary data visualizations

Обычно форматирование столбцов проще и быстрее, чем применение расширения Field Customizer, но оно подходит не для всех сценариев.If you can accomplish your scenario by using column formatting, it’s typically quicker and easier to do that than to use a Field Customizer. Создавать и публиковать модификации с помощью форматирования столбцов могут все, кто может создавать представления в списках и управлять ими.Anyone who can create and manage views in a list can use column formatting to create and publish customizations. Используйте расширение типа Field Customizer для более сложных сценариев, которые невозможно обеспечить с помощью форматирования столбцов.Use a Field Customizer for more advanced scenarios that column formatting does not support.

Приступая к форматированию столбцовGet started with column formatting

Чтобы открыть панель форматирования столбцов, откройте раскрывающееся меню под столбцом.To open the column formatting pane, open the drop-down menu under a column. В разделе Параметры столбца щелкните Форматировать этот столбец.Under Column Settings, choose Format this column.

Если к выбранному столбцу еще не применялось форматирование, эта панель будет выглядеть вот так.If no one has used column formatting on the column you selected, the pane will look like the following.

Панель форматирования столбца с областью для вставки или ввода объекта JSON, а также кнопками для предварительного просмотра, сохранения и отмены

Если форматирование не задано, поле будет отображаться как обычно.A field with no formatting specified uses the default rendering. Чтобы отформатировать столбец, введите в поле объект JSON для форматирования столбца.To format a column, enter the column formatting JSON in the box.

Чтобы просмотреть параметры форматирования, нажмите Просмотреть.To preview the formatting, select Preview. Чтобы сохранить изменения, нажмите Сохранить.To commit your changes, select Save. После сохранения изменений форматирование увидят все пользователи, просматривающие список.When you save, anyone who views the list will see the customization that you applied.

Самый простой способ отформатировать столбец — отредактировать пример и применить его к нужному полю.The easiest way to use column formatting is to start from an example and edit it to apply to your specific field. Следующие разделы содержат примеры, которые можно копировать, вставлять и редактировать.The following sections contain examples that you can copy, paste, and edit for your scenarios. Кроме того, несколько примеров доступны в репозитории SharePoint/sp-dev-column-formatting.There are also several samples available in the SharePoint/sp-dev-column-formatting repository.

Отображение значений поля (базовые настройки)Display field values (basic)

Самый простой способ отформатировать столбец — вставить значение поля в элемент <div />.The simplest column formatting is one that places the value of the field inside a <div /> element. Этот пример подходит для числовых и текстовых полей, а также полей выбора и даты:This example works for number, text, choice, and date fields:

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "div",
   "txtContent": "@currentField"
}

 

Извлечь значения полей некоторых типов немного сложнее.Some field types require a bit of extra work to retrieve their values. Поле пользователя представляется в системе как объект, а отображаемое имя пользователя указывается в свойстве title такого объекта.Person fields are represented in the system as objects, and a person’s display name is contained within that object’s title property. Это тот же пример, но измененный так, чтобы он подходил для поля пользователя:This is the same example, modified to work with the person field:

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "div",
   "txtContent": "@currentField.title"
}

 

Поле подстановки также представляется как объект. Отображаемый текст сохраняется в свойстве lookupValue.Lookup fields are also represented as objects; the display text is stored in the lookupValue property. Этот пример подходит для поля подстановки:This example works with a lookup field:

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "div",
   "txtContent": "@currentField.lookupValue"
}

Применение условного форматированияApply conditional formatting

Форматирование столбцов позволяет применять стили, классы и значки к полям в зависимости от их значений.You can use column formatting to apply styles, classes, and icons to fields, depending on the value inside those fields.

Условное форматирование на основе диапазона чисел (базовые настройки)Conditional formatting based on a number range (basic)

Ниже показан пример условного форматирования, примененного к диапазону чисел.The following image shows an example of conditional formatting applied to a number range.

Предупреждение о степени серьезности 70 с оранжевым фоном

В этом примере условное выражение в стиле Excel (=if) используется для применения класса (sp-field-severity--warning) к родительскому элементу <div />, если значение в текущем поле меньше или равно 70.This example uses an Excel-style conditional expression (=if) to apply a class (sp-field-severity--warning) to the parent <div /> element when the value in the current field is less than or equal to 70. В этом случае поле выделяется, если значение меньше или равно 70, и отображается как обычно, если оно больше 70.This causes the field to be highlighted when the value is less than or equal to 70, and appear normally if it's greater than 70.

JSON
{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
  "elmType": "div",
  "attributes": {
    "class": "=if(@currentField <= 70,'sp-field-severity--warning', '')"
  },
  "children": [
    {
      "elmType": "span",
      "style": {
        "display": "inline-block",
        "padding": "0 4px"
      },
      "attributes": {
        "iconName": "=if(@currentField <= 70,'Error', '')"
      }
    },
    {
      "elmType": "span",
      "txtContent": "@currentField"
    }
  ]
}

Условное форматирование с учетом значения в текстовом поле или поле выбора (расширенные настройки)Conditional formatting based on the value in a text or choice field (advanced)

Ниже показан пример условного форматирования, примененного к текстовому полю или полю выбора.The following image shows an example of conditional formatting applied to a text or choice field:

Поле состояния, в котором элемент "Done" (Готово) выделен зеленым, элемент "Blocked" (Заблокировано) — красным, а элемент "Review" (Проверка) — оранжевым цветом.

Вы можете применить условное форматирование к полям текста или выбора, которые могут содержать фиксированный набор значений.You can apply conditional formatting to text or choice fields that might contain a fixed set of values. В примере ниже применяются различные классы в зависимости от того, какое значение имеет поле: "Готово", "Проверка", "Обнаружены проблемы" или другое.The following example applies different classes depending on whether the value of the field is Done, In Review, Has Issues, or another value. В этом примере класс CSS (sp-field-severity--low, sp-field-severity--good, sp-field-severity--warning, sp-field-severity--severeWarning, sp-field-severity--blocked) применяется к элементу <div /> на основе значения поля.This example applies a CSS class (sp-field-severity--low, sp-field-severity--good, sp-field-severity--warning, sp-field-severity--severeWarning, sp-field-severity--blocked) to the <div /> based on the field's value. Затем он выводит элемент <span /> с атрибутом IconName.It then outputs a <span /> element with an IconName attribute. Этот атрибут автоматически применяет другой класс CSS к элементу <span />, внутри которого отображается значок Office UI Fabric.This attribute automatically applies another CSS class to that <span /> that shows an Office UI Fabric icon inside that element. Наконец, выводится другой элемент <span />, содержащий значение в поле.Finally, another <span /> element is output that contains the value inside the field.

Используйте этот шаблон, чтобы сопоставить разные значения с различными степенями срочности и серьезности.This pattern is useful when you want different values to map to different levels of urgency or severity. Вы можете отредактировать этот пример, чтобы указать собственные значения полей, а также стили и значки, которые необходимо сопоставить с этими значениями.You can start from this example and edit it to specify your own field values and the styles and icons that should map to those values.

JSON
{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
  "elmType": "div",
  "attributes": {
    "class": "=if(@currentField == 'Done', 'sp-field-severity--good', if(@currentField == 'In progress', 'sp-field-severity--low', if(@currentField == 'In review', 'sp-field-severity--warning', if(@currentField == 'Has issues', 'sp-field-severity--severeWarning', 'sp-field-severity--blocked')))) + ' ms-fontColor-neutralSecondary'"
  },
  "children": [
    {
      "elmType": "span",
      "style": {
        "display": "inline-block",
        "padding": "0 4px"
      },
      "attributes": {
        "iconName": "=if(@currentField == 'Done', 'CheckMark', if(@currentField == 'In progress', 'Forward', if(@currentField == 'In review', 'Error', if(@currentField == 'Has issues', 'Warning', 'ErrorBadge'))))"
      }
    },
    {
      "elmType": "span",
      "txtContent": "@currentField"
    }
  ]
}

Применение форматирования на основе диапазонов датApply formatting based on date ranges

Так как даты часто используются для отслеживания крайних сроков и временных шкал ключевых проектов, форматирование часто применяется на основе значения в поле даты и времени.Because dates are often used to track deadlines and key project timelines, a common scenario is to apply formatting based on the value in a date/time field. Чтобы применить форматирование на основе значения этого поля, используйте приведенные ниже шаблоны.To apply formatting based on the value in a date/time field, apply the following patterns.

Форматирование элемента, если дата в столбце предшествует сегодняшней дате или наступает после нее (расширенные настройки)Formatting an item when a date column is before or after today's date (advanced)

На приведенном ниже изображении показано поле, к которому применено условное форматирование даты.The following image shows a field with conditional date formatting applied:

Поле состояния со значением "Overdue" (Просрочено), выделенным красным цветом

В этом примере поле текущей даты окрашивается в красный цвет, если значение в поле "Дата выполнения" элемента предшествует текущим дате и времени.This example colors the current field red when the value inside an item's DueDate is before the current date/time. В отличие от некоторых предыдущих примеров, в этом примере форматирование применяется к одному полю с учетом значения в другом поле.Unlike some of the previous examples, this example applies formatting to one field by looking at the value inside another field. Обратите внимание на то, что для ссылки на поле "DueDate" (Дата выполнения) используется синтаксис [$FieldName].Note that DueDate is referenced using the [$FieldName] syntax. FieldName — это внутреннее имя поля.FieldName is assumed to be the internal name of the field. В этом примере также используется специальное значение @now, которое можно использовать в полях даты и времени. Это значение сопоставляется с текущими датой и временем, которые определяются при загрузке списка.This example also takes advantage of a special value that can be used in date/time fields - @now, which resolves to the current date/time, evaluated when the user loads the list view.

Примечание

Если в имени поля есть пробелы, они определяются как _x0020_.If you have spaces in the field name, those are defined as _x0020_. Например, имя поля "Due Date" (Дата выполнения) должно писаться так: $Due_x0020_Date.For example, a field named "Due Date" should be referenced as $Due_x0020_Date.

JSON
{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
  "elmType": "div",
  "debugMode": true,
  "txtContent": "@currentField",
  "style": {
    "color": "=if([$DueDate] <= @now, '#ff0000', '')"
  }
}

Форматирование элементов с учетом произвольных дат (расширенные настройки)Formatting items based on arbitrary dates (advanced)

Чтобы сравнить значение поля даты и времени с датой, отличной от @now, используйте шаблон, приведенный в примере ниже.To compare the value of a date/time field against a date that's not @now, follow the pattern in the following example. Здесь поле текущей даты окрашивается в красный цвет, если дата выполнения назначена на завтра или ранее.The following example colors the current field red if the due date was <= tomorrow. Для этого используются математические операции с датой.This is accomplished using date math. Вы можете добавить миллисекунды к любой дате, чтобы получить новую дату.You can add milliseconds to any date and the result will be a new date. Например, чтобы добавить к дате один день, добавьте 24*60*60*1000 (результатом будет 86 400 000).For example, to add a day to a date, you'd add (24*60*60*1000 = 86,400,000).

В этом примере демонстрируется альтернативный синтаксис для условного выражения с использованием тернарного (?) оператора внутри дерева абстрактного синтаксиса.This example demonstrates an alternate syntax to express a conditional expression, using the ternary (?) operator inside an abstract syntax tree.

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "div",
   "txtContent": "@currentField",
   "style": {
      "color": {
         "operator": "?",
         "operands": [
            {
               "operator": "<=",
               "operands": [
                  "[$DueDate]",
                  {
                     "operator": "+",
                     "operands": [
                        "@now",
                        86400000
                     ]
                  }
               ]
            },
            "#ff0000",
            ""
         ]
      }
   }
}

 

Чтобы сравнить значение поля даты и времени с другой константой даты, преобразуйте строку в дату с помощью метода Date().To compare a date/time field value against another date constant, use the Date() method to convert a string to a date. Приведенный ниже пример кода окрашивает текущее поле в красный цвет, если значение в поле "DueDate" (Дата выполнения) предшествует дате 22.03.2017.The following example colors the current field red if the value in the DueDate field is before 3/22/2017.

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "div",
   "txtContent": "@currentField",
   "style": {
      "color": {
         "operator": "?",
         "operands": [
            {
               "operator": "<=",
               "operands": [
                  "[$DueDate]",
                  {
                     "operator": "Date()",
                     "operands": [
                        "3/22/2017"
                     ]
                  }
               ]
            },
            "#ff0000",
            ""
         ]
      }
   }
}

Создание интерактивных действийCreate clickable actions

Форматирование столбцов позволяет показывать гиперссылки для перехода на другие веб-страницы или запускать пользовательские функции.You can use column formatting to provide hyperlinks that go to other webpages, or start custom functionality. Можно показывать только статические ссылки, параметризируемые с использованием значений из полей в списке.This functionality is limited to static links that can be paramaterized with values from fields in the list. Форматирование столбцов невозможно использовать для вывода ссылок на протоколы, отличные от http://, https:// и mailto:.You can't use column formatting to output links to protocols other than http://, https://, or mailto:.

В этом примере показано, как преобразовать текстовое поле с финансовыми символами в гиперссылку, которая позволяет перейти на страницу Yahoo Finance с актуальными котировками для соответствующих символов.This example shows how to turn a text field that contains stock ticker symbols into a hyperlink that targets the Yahoo Finance real-time quotes page for that stock ticker. В этом примере используется оператор +, позволяющий добавить значение текущего поля к статической гиперссылке http://finance.yahoo.com/quote/.The example uses a + operator that appends the current field value to the static hyperlink http://finance.yahoo.com/quote/. Этот шаблон также можно использовать, если вы хотите предоставить пользователям возможность просматривать контекстную информацию, связанную с элементом, или запустить бизнес-процесс для текущего элемента, если эта информация или процесс доступны по гиперссылке, параметризуемой с помощью значений из элемента списка.You can extend this pattern to any scenario in which you want users to view contextual information related to an item, or you want to start a business process on the current item, as long as the information or process can be accessed via a hyperlink parameterized with values from the list item.

Списки акций с финансовыми символами, преобразованными в гиперссылки

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "a",
   "txtContent": "@currentField",
   "attributes": {
      "target": "_blank",
      "href": "='http://finance.yahoo.com/quote/' + @currentField"
   }
}

Добавление в поле кнопки действия (расширенные настройки)Add an action button to a field (advanced)

На рисунке ниже приведены кнопки действия, добавленные в поле.The following image shows action buttons added to a field.

Поле "Кому назначено" с кнопками почты, добавленными к именам

С помощью форматирования столбцов можно отображать ссылки на быстрые действия рядом с полями.You can use column formatting to render quick action links next to fields. В этом примере, предназначенном для поля пользователя, отображаются два элемента в родительском элементе <div />:The following example, intended for a person field, renders two elements inside the parent <div /> element:

JSON
{
    "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
    "elmType": "div",
    "children": [
        {
            "elmType": "span",
            "style": {
                "padding-right": "8px"
            },
            "txtContent": "@currentField.title"
        },
        {
            "elmType": "a",
            "attributes": {
                "iconName": "Mail",
                "class": "sp-field-quickActions",
                "href": {
                    "operator": "+",
                    "operands": [
                        "mailto:",
                        "@currentField.email",
                        "?subject=Task status&body=Hey, how is your task coming along?.\r\n---\r\n",
                        "@currentField.title",
                        "\r\nClick this link for more info. http://contoso.sharepoint.com/sites/ConferencePrep/Tasks/Prep/DispForm.aspx?ID=",
                        "[$ID]"
                    ]
                }
            }
        }
    ]
}

Создание простой визуализации данныхCreate simple data visualizations

Форматирование столбцов позволяет сочетать условные и арифметические операции для выполнения базовой визуализации данных.Use column formatting to combine conditional and arithmetical operations to achieve basic data visualizations.

Форматирование числового столбца в виде гистограммы (расширенные настройки)Format a number column as a data bar (advanced)

На рисунке ниже приведен числовой столбец, отформатированный в виде гистограммы.The following image shows a number column formatted as a data bar.

Список "Трудозатраты" с числовыми элементами списка, отображаемыми в виде столбцов

В этом примере для визуализации числового поля @currentField в виде гистограммы применяются стили background-color и border-top.This example applies background-color and border-top styles to create a data bar visualization of @currentField, which is a number field. Размер столбиков зависит от того, каков атрибут width. Ему присваивается 100%, если значение больше 95, и (@currentField * 100 / 95)% в противном случае. The bars are sized differently for different values based on the way the width attribute is set - it's set to 100% when the value is greater than 95, and (@currentField * 100 / 95)% otherwise. Чтобы применить этот пример к своему числовому столбцу, вы можете настроить граничное условие (20) в соответствии с максимальным предполагаемым значением в поле и изменить формулу, чтобы указать, на сколько должен увеличиваться столбец в зависимости от значения в поле.To fit this example to your number column, you can adjust the boundary condition (20) to match the maximum anticipated value inside the field, and change the equation to specify how much the bar should grow depending on the value inside the field.

JSON
{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
  "elmType": "div",
  "txtContent": "@currentField",
  "attributes": {
    "class": "sp-field-dataBars"
  },
  "style": {
    "width": "=if(@currentField > 95, '100%', toString(@currentField * 100 / 95) + '%')"
  }
}

На приведенном ниже изображении показан список, к которому добавлены значки тенденций к увеличению или уменьшению.The following image shows a list with trending up/trending down icons added:

Список, возле элементов которого расположены значки тенденций к увеличению и уменьшению

В этом примере используются два числовых поля Before и After, значения которых можно сравнить.This example relies on two number fields, Before and After, for which the values can be compared. Соответствующий значок тенденции отображается рядом с полем After в зависимости от значения этого поля по сравнению со значением в поле Before.It shows the appropriate trending icon next to the After field, depending on that field's value compared to the value in Before. Если значение поля After выше, используется sp-field-trending--up, а если значение поля After ниже, используется sp-field-trending--down.sp-field-trending--up is used when After's value is higher; sp-field-trending--down is used when After's value is lower.

JSON
{
    "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
    "elmType": "div",
    "children": [
        {
            "elmType": "span",
            "attributes": {
                "class": {
                    "operator": "?",
                    "operands": [
                        {
                            "operator": ">",
                            "operands": [
                                "[$After]",
                                "[$Before]"
                            ]
                        },
                        "sp-field-trending--up",
                        "sp-field-trending--down"
                    ]
                },
                "iconName": {
                    "operator": "?",
                    "operands": [
                        {
                            "operator": ">",
                            "operands": [
                                "[$After]",
                                "[$Before]"
                            ]
                        },
                        "SortUp",
                        {
                            "operator": "?",
                            "operands": [
                                {
                                    "operator": "<",
                                    "operands": [
                                        "[$After]",
                                        "[$Before]"
                                    ]
                                },
                                "SortDown",
                                ""
                            ]
                        }
                    ]
                }
            }
        },
        {
            "elmType": "span",
            "txtContent": "[$After]"
        }
    ]
}

Создание кнопки для запуска потокаCreate a button to launch a Flow

На приведенном ниже снимке экрана показан список, где в столбец действий добавлена кнопка потокаThe following screenshot shows a list with a Flow button added to the Action column:

снимок экрана с примером

С помощью форматирования столбцов вы можете создавать кнопки, при нажатии которых запускаются потоки для соответствующих элементов списка.You can use column formatting to create buttons that, when selected, run Flows on the corresponding list item. Если поток настроен так, чтобы получать данные от пользователя перед запуском, то после нажатия кнопки отобразится панель запуска потока.If the Flow is configured to gather data from the end user before running, the Flow Launch Panel will be displayed after choosing the button. В противном случае поток просто запустится.Otherwise, the Flow will just run.

Чтобы использовать приведенный ниже пример, необходимо указать ИД нужного потока.To use the sample below, you must substitute the ID of the Flow you want to run. Этот ИД хранится в атрибуте customRowAction элемента button.This ID is contained within the customRowAction attribute inside the button element. Чтобы получить идентификатор потока, выполните указанные ниже действия.To obtain a Flow's ID:

  1. Щелкните "Поток" > "Просмотреть ваши потоки" в том списке SharePoint, где настроен поток.Choose Flow > See your flows in the SharePoint list where the Flow is configured.
  2. Выберите поток, который необходимо запустить.Choose the Flow you want to run.
  3. Скопируйте идентификатор из окончания URL-адреса.Copy the ID from the end of the URL.
JSON
{
    "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
    "elmType": "span",
    "style": {
        "color": "#0078d7"
    },
    "children": [
    {
        "elmType": "span",
        "attributes": {
            "iconName": "Flow"
        }
    },
    {
        "elmType": "button",
        "style": {
            "border": "none",
            "background-color": "transparent",        
            "color": "#0078d7",    
            "cursor": "pointer"
        },
        "txtContent": "Send to Manager",
        "customRowAction": {
            "action": "executeFlow",
            "actionParams": "{\"id\": \"183bedd4-6f2b-4264-855c-9dc7617b4dbe\"}"
        }          
    }        
  ]
}

Поддерживаемые типы столбцовSupported column types

Форматировать можно следующие типы столбцов:The following column types support column formatting:

Следующие типы столбцов не поддерживаются:The following are not currently supported:

Рекомендации по стилюStyle guidelines

Предопределенные классыPredefined classes

Вы можете использовать указанные ниже предопределенные классы.You can use the following predefined classes for several common scenarios.

Имя классаClass name Снимок экранаScreenshot
sp-field-customFormatBackgroundsp-field-customFormatBackground Указывает параметры заполнения и поля для всех классов, использующих фон.Specifies the padding and margins for all classes that use backgrounds.
sp-field-severity--goodsp-field-severity--good Зеленое поле с текстом "Готово" и флажком
sp-field-severity--lowsp-field-severity--low Белое поле с текстом "Выполняется" и стрелкой
sp-field-severity--warningsp-field-severity--warning Желтое поле с текстом "Проверка" и значком предупреждения
sp-field-severity--severeWarningsp-field-severity--severeWarning Оранжевое поле с текстом "Обнаружены проблемы" и значком предупреждения
sp-field-severity--blockedsp-field-severity--blocked Красное поле с текстом "Заблокировано" и значком X
sp-field-dataBarssp-field-dataBars Синий прямоугольник с числом 4
sp-field-trending--upsp-field-trending--up Зеленая стрелка с числом 500
sp-field-trending--downsp-field-trending--down Красная стрелка с числом 100
sp-field-quickActionssp-field-quickActions Имя со значком почты

Примечание

Значки, указанные выше для классов sp-field-severity НЕ входят в состав класса.The icons shown above for the sp-field-severity classes are NOT part of the class. Включается только цвет фона.Only the background color is included. Значки можно добавлять с помощью атрибута iconName.Icons can be added by using the iconName attribute.

Помимо указанных выше классов можно использовать классы (например, цвет темы, оформление, сетка и т. д.), определяемые Office UI Fabric.In addition to the classes listed above, the classes (such as the theme color, typography, grid system, etc.) defined by the Office UI Fabric can be used. Дополнительные сведения см. на веб-сайте Fabric.For details, see the Fabric website.

Предопределенные значкиPredefined icons

Вы можете использовать предопределенные значки из Office UI Fabric.You can use predefined icons from Office UI Fabric. Дополнительные сведения см. на веб-сайте Fabric.For details, see the Fabric website.

Создание собственной нотации JSONCreating custom JSON

Вы можете легко создать собственную нотацию JSON для форматирования столбцов, если понимаете схему.Creating custom column formatting JSON from scratch is simple if you understand the schema. Чтобы создать собственные параметры форматирования столбцов:To create your own custom column formatting:

  1. Скачайте Visual Studio Code.Download Visual Studio Code. Это можно скачать быстро и бесплатно.It's free and fast to download.

  2. В Visual Studio Code создайте пустой файл и сохраните его с расширением JSON.In Visual Studio Code, create a new file, and save the empty file with a .json file extension.

  3. Вставьте приведенные ниже строки кода в пустой файл.Paste the following lines of code into your empty file.

    JSON
     {
     "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json"
     }
    

    Теперь вы можете использовать функции проверки и автозаполнения при создании нотации JSON.You now have validation and autocomplete to create your JSON. Вы можете начать добавлять нотацию JSON после первой строки, определяющей расположение схемы.You can start adding your JSON after the first line that defines the schema location.

Совет

Чтобы отобразить предложения свойств и значений, вы можете в любой момент нажать клавиши CTRL+ПРОБЕЛ.At any point, select Ctrl+Space to have Visual Studio Code offer suggestions for properties and values. Дополнительные сведения см. в статье Редактирование JSON с помощью Visual Studio Code.For more information, see Editing JSON with Visual Studio Code.

Совет

Рекомендации SharePoint предоставляют бесплатную веб-часть Средство форматирования столбцов, которую можно использовать для редактирования и применения форматов непосредственно в браузере.SharePoint Patterns and Practices provides a free web part, Column Formatter, that can be used to edit and apply formats directly in the browser.

Подробная справка по синтаксисуDetailed syntax reference

elmTypeelmType

Указывает тип создаваемого элемента.Specifies the type of element to create. Допустимые элементы:Valid elements include:

Любое другое значение приведет к ошибке.Any other value will result in an error.

Элементы buttonbutton elements

Элементы Button можно использовать для запуска определенного действия над родительским элементом. Button elements can be used to launch a specific action on the parent item. Каждый элемент button имеет требуемое свойство customRowAction, которое определяет действие action, выполняемое при нажатии кнопки.Every button element has a requred property, customRowAction, that specifies an action that's taken when the button is clicked. Это действие должно принимать одно из следующих значений:This action must be one of the following values:

JSON
{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
  "elmType": "button",
  "txtContent": "Open this item",
  "customRowAction": {
    "action": "defaultClick"
  }
}
JSON
{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
  "elmType": "button",
  "txtContent": "Share this item",
  "customRowAction": {
    "action": "share"
  }
}

txtContenttxtContent

Необязательно свойство, которое задает текстовое содержимое элемента, указанного с помощью свойства elmType.An optional property that specifies the text content of the element specified by elmType. Значение этого свойства может представлять собой строку (в том числе специальную) или объект Expression.The value of this property can either be a string (including special strings) or an Expression object.

stylestyle

Необязательно свойство, которое задает атрибуты стиля, применяемые к элементу, который указан с помощью свойства elmType.An optional property that specifies style attributes to apply to the element specified by elmType. Это объект с парами имя-значение, которые соответствуют именам и значениям CSS.This is an object with name-value pairs that correspond to CSS names and values. Значение каждого из свойств объекта style может представлять собой строку (в том числе специальную) или объект Expression.The values of each property in the style object can either be a string (including special strings) or an Expression object. Поддерживаются следующие атрибуты style:The following style attributes are allowed.

'background-color'
'fill'
'background-image'
'border'
'border-bottom'
'border-bottom-color'
'border-bottom-style'
'border-bottom-width'
'border-color'
'border-left'
'border-left-color'
'border-left-style'
'border-left-width'
'border-right'
'border-right-color'
'border-right-style'
'border-right-width'
'border-style'
'border-top'
'border-top-color'
'border-top-style'
'border-top-width'
'border-width'
'outline'
'outline-color'
'outline-style'
'outline-width'
'border-bottom-left-radius'
'border-bottom-right-radius'
'border-radius'
'border-top-left-radius'
'border-top-right-radius'
'box-decoration-break'
'box-shadow'
'box-sizing'

'overflow-x'
'overflow-y'
'overflow-style'
'rotation'
'rotation-point'

'opacity'
'cursor'

'height'
'max-height'
'max-width'
'min-height'
'min-width'
'width'

'flex-grow'
'flex-shrink'
'flex-flow'
'flex-direction'
'flex-wrap'
'flex'
'justify-content'
'align-items'

'box-align'
'box-direction'
'box-flex'
'box-flex-group'
'box-lines'
'box-ordinal-group'
'box-orient'
'box-pack'

'font'
'font-family'
'font-size'
'font-style'
'font-variant'
'font-weight'
'font-size-adjust'
'font-stretch'

'grid-columns'
'grid-rows'

'margin'
'margin-bottom'
'margin-left'
'margin-right'
'margin-top'

'column-count'
'column-fill'
'column-gap'
'column-rule'
'column-rule-color'
'column-rule-style'
'column-rule-width'
'column-span'
'column-width'
'columns'

'padding'
'padding-bottom'
'padding-left'
'padding-right'
'padding-top'

'bottom'
'clear'
'clip'
'display'
'float'
'left'
'overflow'
'position' 
'right'
'top'
'visibility'
'z-index'

'border-collapse'
'border-spacing'
'caption-side'
'empty-cells'
'table-layout'

'color'
'direction'
'letter-spacing'
'line-height'
'text-align'
'text-decoration'
'text-indent'
'text-transform'
'unicode-bidi'
'vertical-align'
'white-space'
'word-spacing'
'hanging-punctuation'
'punctuation-trim'
'text-align-last'
'text-justify'
'text-outline'
'text-shadow'
'text-wrap'
'word-break'
'word-wrap'

В приведенном ниже примере показано значение объекта style.The following example shows the value of a style object. В этом примере будут применены два свойства style (padding и background-color).In this example, two style properties (padding and background-color) will be applied. padding — это жестко заданное значение строки.The padding value is a hard-coded string value. Значение background-color — это объект Expression, который окрашивается в красный (#ff0000) или зеленый (#00ff00) цвет в зависимости от того, меньше ли 40 значение текущего поля (указывается @currentField).The background-color value is an Expression that is evaluated to either red (#ff0000) or green (#00ff00) depending on whether the value of the current field (specified by @currentField) is less than 40. Дополнительные сведения см. в разделе "Объект Expression".For more information, see the Expression object section.

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "padding": "4px",
   "background-color": {
      "operator": "?",
      "operands": [
         {
            "operator": "<",
            "operands": [
               "@currentField",
               40
            ]
         },
         "#ff0000",
         "#00ff00"
      ]
   }
}

attributesattributes

Необязательно свойство, которое задает дополнительные атрибуты, добавляемые к элементу, который указан с помощью свойства elmType.An optional property that specifies additional attributes to add to the element specified by elmType. Это объект с парами имя-значение.This is an object with name-value pairs. Допустимые имена атрибутов:Attribute names must be one of the following:

Любое другое имя атрибута приведет к ошибке.Any other attribute name will result in an error. Значения атрибутов могут представлять собой объекты Expression или строки.Attribute values can either be Expression objects or strings. В следующем примере к элементу, указанному с помощью свойства elmType, добавляются два атрибута (target и href).The following example adds two attributes (target and href) to the element specified by elmType. Атрибут target жестко задан в строке.The target attribute is hard-coded to a string. Атрибут href — это выражение, которое вычисляется в среде выполнения по формуле http://finance.yahoo.com/quote/ + значение текущего поля (@currentField).The href attribute is an expression that will be evaluated at runtime to http://finance.yahoo.com/quote/ + the value of the current field (@currentField).

JSON
{
        "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
    "target": "_blank",
    "href": "='http://finance.yahoo.com/quote/' + @currentField"
}

childrenchildren

Необязательно свойство, которое задает дочерние элементы для элемента, указанного с помощью свойства elmType.An optional property that specifies child elements of the element specified by elmType. Это значение задается в качестве массива объектов elm.The value is specified as an array of elm objects. Возможен произвольный уровень вложения.There can be an arbitrary level of nesting. Если элемент содержит свойство txtContent, дочерние свойства игнорируются.If an element has the txtContent property, the child properties are ignored.

debugModedebugMode

Необязательно свойство, используемое для отладки.An optional property that is meant for debugging. Выводит сообщения об ошибках и записывает предупреждения в журнале консоли.It outputs error messages and logs warnings to the console.

ВыраженияExpressions

Значения свойств txtContent, style и attribute можно представить в виде выражений для вычисления в среде выполнения с учетом контекста текущего поля (или строки).Values for txtContent, style properties, and attribute properties can be expressed as expressions, so that they are evaluated at runtime based on the context of the current field (or row). В объекты Expression можно вложить другие объекты Expression.Expression objects can be nested to contain other Expression objects.

Выражения в стиле ExcelExcel-style expressions

Все выражения в стиле Excel начинаются со знака равенства (=).All Excel-style expressions begin with an equal (=) sign.

Это простое условное выражение вычисляется как none, если @me не равно [$Author.email], и вычисляется как `` в противном случае:This simple conditional expression evaluates to none if @me is not equal to [$Author.email], and evaluates to `` otherwise:

JSON
=if(@me != [$Author.email], 'none', '') 

Более сложные утверждения if/else могут быть записаны следующим образом:More complex if/else statements can be written like this:

JSON
=if([$Sentiment] <= 0.3, 'sp-field-severity--blocked', if([$Sentiment] < 0.9,'sp-field-severity--warning','sp-field-severity--good')) 

Не условные операторы, которые принимают один или два операнда, могут быть записаны следующим образом:Non-conditional operators that take one or two operands can be written like this:

JSON
=[$foo] * -7 
JSON
=sin(@currentField) 
JSON
=toString(60 + (sin(6.2831853 * @currentField) * 60)) 

Выражения деревьев абстрактного синтаксисаAbstract Syntax Tree expressions

В этом примере показан объект Expression, который выполняет следующее выражение:The following example contains an Expression object that performs the following expression:

(@currentField > 40) ? '100%' : (((@currentField * 2.5).toString() + '%')

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "operator": "?",
   "operands": [
      {
         "operator": ">",
         "operands": [
            "@currentField",
            "40"
         ]
      },
      "100%",
      {
         "operator": "+",
         "operands": [
            {
               "operator": "toString()",
               "operands": [
                  {
                     "operator": "*",
                     "operands": [
                        "@currentField",
                        2.5
                     ]
                  }
               ]
            },
            "%"
         ]
      }
   ]
}

ОператорыOperators

Операторы задают тип выполняемой операции.Operators specify the type of operation to perform. Допустимы такие операторы:The following operators are valid values:

Бинарные операторы. Стандартные арифметические бинарные операторы, предусматривающие два операнда:Binary operators - The following are the standard arithmetic binary operators that expect two operands:

Унарные операторы. Стандартные унарные операторы, требующие только один операнд:Unary operators - The following are standard unary operators that expect only one operand:

Условный оператор. Вот он:Conditional operator - The conditional operator is:

Он позволяет получить выражение, эквивалентное a ?This is to achieve an expression equivalent to a ? b : c. Если выражение a принимает значение true, результатом является b. В противном случае результат выражения — c.b : c, where if the expression a evaluates to true, then the result is b, else the result is c.

operandsoperands

Задает параметры, или операнды, для выражения.Specifies the parameters, or operands for an expression. Это массив объектов Expression или базовые значения.This is an array of Expression objects or base values.

Значения специальных строкSpecial string values

Значения свойств txtContent, style и attribute могут представлять собой строки или объекты Expression.The values for txtContent, styles, and attributes can be either strings or Expression objects. Поддерживаются несколько шаблонов специальных строк для извлечения значений из полей в списке и контексте пользователя.A few special string patterns for retrieving values from the fields in the list and the user's context are supported.

"@currentField""@currentField"

Возвращает значение текущего поля.Will evaluate to the value of the current field.

Поля некоторых типов представлены в виде объектов.Some field types are represented as objects. Чтобы вывести значение из объекта, сошлитесь на определенное свойство в этом объекте.To output a value from an object, refer to a particular property inside that object. Например, если текущее поле представляет собой поле пользователя или группы, укажите @currentField.title, чтобы получить имя пользователя, которое обычно отображается в представлениях списка.For example, if the current field is a person/group field, specify @currentField.title to retrieve the person's name, which is normally displayed in list views. Ниже приведены типы полей, которые представлены в виде объектов со списком их свойств.The following are the field types that are represented as objects with a list their properties.

Примечание

@currentField.title возвращает имя пользователя по умолчанию.The @currentField.title returns a person's name by default. Но если параметр "Show Field" (Показать поле) для поля пользователя был настроен, он может изменить значение свойства title.However, if the person field's Show Field has been adjusted, it may change the value of the title property. Например, если параметр "Show Field" (Показать поле) поля пользователя настроен как "Department" (Отдел), это поле будет содержать сведения об отделе пользователя для свойства title.For example, a person field with the Show Field configured as Department will have the person's department for the title property.

Поля пользователейPeople fields

Объект поля пользователя имеет указанные ниже свойства (приведены примеры значений).The people field object has the following properties (with example values):

JSON
{
   "id": "122",
   "title": "Kalya Tucker",
   "email": "Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.",
   "sip": "Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.",
   "picture": "https://contoso.sharepoint.com/kaylat_contoso_com_MThumb.jpg?t=63576928822"
}

Поля даты и времениDate/Time fields

Значения полей даты и времени можно получить разными способами в зависимости от необходимого формата даты.The value of Date/Time fields can be retrieved a few different ways, depending on the date format you'd like to display. Поддерживаются следующие способы преобразования значений дат в определенные форматы:The following methods for converting date values to specific formats are supported:

Например, при использовании следующей нотации JSON текущее поле (если это поле даты) будет отображено в виде строки с датой и временем:For example, the following JSON will display the current field (assuming it's a date field) as a date and time string.

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "div",
   "txtContent": {
        "operator": "toLocaleString()",
        "operands" : ["@currentField"]
    }
}

Поля подстановкиLookup fields

Объект поля подстановки имеет указанные ниже свойства (приведены примеры значений).The lookup field object has the following properties (with example values):

JSON
{
   "lookupId": "100",
   "lookupValue": "North America",
}

 

Ниже показано, как можно применить поле подстановки к текущему полю.The following example shows how a lookup field might be used on a current field.

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "a",
   "txtContent": "@currentField.lookupValue",
   "attributes": {
      "href": {
         "operator": "+",
         "operands": [
            "https://contoso.sharepoint.com/teams/Discovery/Lists/Regions/DispForm.aspx?ID=",
            "@currentField.lookupId"
         ]
      },
      "target": "_blank"
   }
}

Поля гиперссылокHyperlink fields

Объект поля гиперссылки имеет указанное ниже свойство (приведен пример значения).The hyperlink field object has the following property (with example value):

JSON
{
   "desc": "SharePoint Patterns and Practices",
}

 

Для ссылки на значение URL-адреса используйте @currentField.To reference the URL value, use @currentField.

Ниже показано, как можно применить поле гиперссылки к текущему полю.The following example shows how a hyperlink field might be used on a current field.

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "a",
   "txtContent": "@currentField.desc",
   "attributes": {
      "href": "@currentField",
      "target": "_blank"
   }
}

"[$FieldName]""[$FieldName]"

Столбец форматируется в контексте всей строки.The column is formatted within the context of the entire row. Вы можете использовать этот контекст для ссылки на значения других полей в пределах одной строки, указав внутреннее имя поля, заключенного в квадратные скобки, со знаком доллара перед ним: [$InternalName].You can use this context to reference the values of other fields within the same row by specifying the internal name of the field surrounded by square brackets and preceeded by a dollar sign: [$InternalName]. Например, чтобы получить значение поля с внутренним именем "MarchSales", используйте [$MarchSales].For example, to get the value of a field with an internal name of "MarchSales", use [$MarchSales].

Если значение поля представляет собой объект, можно получить доступ к свойствам этого объекта.If the value of a field is an object, the object's properties can be accessed. Например, чтобы получить доступ к свойству "Title" (Название) поля пользователя "SalesLead" (Потенциальный клиент), укажите "[$SalesLead.title]".For example, to access the "Title" property of a person field named "SalesLead", use "[$SalesLead.title]".

"@currentWeb""@currentWeb"

Вычисляет абсолютный URL-адрес для сайта.This will evaluate to the absolute url for the site. Это аналогично значению webAbsoluteUrl в контексте страницы.This is equivalent to the webAbsoluteUrl value within the page context.

"@me""@me"

Вычисляет электронный адрес текущего пользователя, выполнившего вход.This will evaluate to the email address of the current logged in user.

Это поле может использоваться для отображения электронного адреса текущего пользователя, но, скорее всего, оно будет указано в условиях.This field can be used to display the current user's email address, but more likely it will be used within conditions. Приведенный ниже пример кода задает красный цвет для поля пользователя, если значение этого поля соответствует текущему вошедшему пользователю, и синий, если не соответствует.The following is an example of setting the color for a person field to red when it is equal to the current logged in user and blue otherwise:

JSON
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "div",
   "txtContent": "@currentField.title",
   "style": {
      "color": {
         "operator": "?",
         "operands": [
            {
               "operator": "==",
               "operands": [
                  "@me",
                  "@currentField.email"
               ]
            },
            "red",
            "blue"
         ]
      }
   }
}

"@now""@now"

Возвращает текущие дату и время.This will evaluate to the current date and time.

"@window.innerHeight""@window.innerHeight"

Возвращает число, соответствующее высоте окна браузера (в пикселях) при отображении списка.This will evaluate to a number equal to the height of the browser window (in pixels) when the list was rendered.

"@window.innerWidth""@window.innerWidth"

Возвращает число, соответствующее ширине окна браузера (в пикселях) при отображении списка.

 

Категория: Статьи
Просмотров: 5105